package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;
    //登录
    @Override
    public ResultInfo login(String username, String password) {
        //1.调用mapper查询，没找到用户名时返回失败信息：用户名不存在
        Employee employee=employeeMapper.findByUsername(username);
        if (employee == null) {
            return ResultInfo.error("用户名不存在");
        }
        //2.将输入的密码加密后与查询到的密码对比，不匹配的话返回失败信息：密码错误
        String passwordWithMd5 = SecureUtil.md5(password);
        if (!StringUtils.equals(passwordWithMd5, employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        //3.判断状态码，为0时，返回失败信息：用户被禁用
        if (employee.getStatus() == Employee.STATUS_DISABLE) {
            return ResultInfo.error("用户被禁用");
        }
        //4.都成功时，返回ResultInfo
        return ResultInfo.success(employee);
    }
    //根据Name查询
    @Override
    public List<Employee> findByName(String name) {
        return employeeMapper.findByName(name);
    }
    //保存
    @Override
    public void save(Employee employee) {
        //1.补齐参数
        employee.setId(IdUtil.getSnowflake(1,1).nextId());//雪花算法生成唯一ID
        employee.setPassword(SecureUtil.md5("123"));//设置默认密码并加密
        employee.setStatus(Employee.STATUS_ENABLE);//默认状态激活
//        employee.setCreateTime(new Date());
//        employee.setUpdateTime(new Date());
//        //todo 操作人
//        employee.setCreateUser(1L);
//        employee.setUpdateUser(1L);
        //2.调用mapper
        employeeMapper.save(employee);
    }
    //根据id查询员工
    @Override
    public Employee findById(Long id) {
        return employeeMapper.findById(id);
    }
    //修改员工
    @Override
    public void update(Employee employee) {
        //1.重新赋值
//        employee.setUpdateTime(new Date());
//        employee.setUpdateUser(1L);
        //2.调用
        employeeMapper.update(employee);
    }


}
